package com.jxy.pay.factory;

import com.jxy.pay.enums.PayTypeEnum;
import com.jxy.pay.strategy.PayStrategy;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName PayFactory
 * @Description 支付策略工厂
 * @Author zheng
 * @Date 2022/10/11 20:46
 * @Version 1.0
 **/
@Slf4j
public class PayStrategyFactory {
    /**
     * 支付策略缓存
     */
    private static final ConcurrentHashMap<String, PayStrategy> PAY_STRATEGY_MAP = new ConcurrentHashMap<>();

    public static PayStrategy getPayStrategy(String payType) {
        //缓存中获取到则直接返回(单例)
        PayStrategy payStrategy = PAY_STRATEGY_MAP.get(payType);
        if (payStrategy != null) {
            return payStrategy;
        }
        String classFullName = PayTypeEnum.getClassFullName(payType);
        if (StringUtils.isNotBlank(classFullName)) {
            try {
                //通过反射生成一个PayStrategy实例，并存入缓存中。
                Class<?> clazz = Class.forName(classFullName);
                PayStrategy newInstance = (PayStrategy) clazz.newInstance();
                PAY_STRATEGY_MAP.put(payType, newInstance);
                return newInstance;
            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
                log.error("类生成失败，{}", classFullName);
                throw new RuntimeException(e);
            }
        } else {
            log.error("不合法的支付方式：{}", payType);
            throw new IllegalArgumentException("不合法的支付方式");
        }
    }
}
